package com.changgou.user.controller;

import com.changgou.entity.PageResult;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.user.config.TokenDecode;
import com.changgou.user.pojo.User;
import com.changgou.user.service.UserService;
import com.changgou.user.utils.ValidateCodeUtils;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;


@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private TokenDecode tokenDecode;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String OLD_PHONONE_CHANGE_ = "old_phonone_change_";
    private static final String NEW_PHONONE_CHANGE_ = "new_phonone_change_";

    @GetMapping("/changephone/{mobile}/{smscode}")
    public Result changephone(@PathVariable("mobile") String mobile,@PathVariable("smscode") String smscode){
        String redisCode = (String)redisTemplate.boundValueOps(NEW_PHONONE_CHANGE_+mobile).get();
        if (redisCode!=null&&smscode!=null&&redisCode.equals(smscode)){
            String username = tokenDecode.getUserInfo().get("user_name");  //根据token获取用户名
            User user = userService.findById(username);
            user.setPhone(mobile);
            userService.update(user);
            return new Result(false, StatusCode.ERROR,"用户手机号修改成功");
        }
        return new Result(false, StatusCode.ERROR,"输入验证码校验错误");
    }
    @GetMapping("/sendnewphone")
    public Result sendphonesms(@RequestParam("mobile") String mobile){
        Map map = new HashMap();
        map.put("phone",mobile);
        List list = userService.findList(map);
        if (list!=null&&list.size()>0){
            return new Result(false, StatusCode.ERROR,"手机号已注册");
        }
        try {
            Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
            System.out.println("生成的验证码："+validateCode);
            //SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, mobile, validateCode.toString());
            redisTemplate.opsForValue().set(NEW_PHONONE_CHANGE_+mobile,validateCode.toString());
            redisTemplate.expire(NEW_PHONONE_CHANGE_+mobile,2, TimeUnit.MINUTES);//保存2分钟
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"验证码发送失败");
        }
        return new Result(true,StatusCode.OK,"发送消息成功");
    }

    @GetMapping("/checkoldphone")
    public Result checkoldphone(@RequestParam("smsCode") String smsCode){
        String username = tokenDecode.getUserInfo().get("user_name");  //根据token获取用户名
        User user = userService.findById(username);
        String oldphone = user.getPhone();
        String redisCode = (String)redisTemplate.boundValueOps(OLD_PHONONE_CHANGE_+oldphone).get();
        if (redisCode!=null&&smsCode!=null&&redisCode.equals(smsCode)){
            return new Result(true, StatusCode.OK,"验证码校验成功");
        }
        return new Result(false, StatusCode.ERROR,"输入验证码校验错误");
    }

    @GetMapping("/sendoldphonesms")
    public Result sendoldphonesms(){
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        System.out.println("生成的验证码："+validateCode);
        try {
            String username = tokenDecode.getUserInfo().get("user_name");  //根据token获取用户名
            User user = userService.findById(username);
            String oldphone = user.getPhone();
            //SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, oldphone, validateCode.toString());
            //将短信保存在redis中5分钟
            redisTemplate.opsForValue().set(OLD_PHONONE_CHANGE_+oldphone,validateCode.toString());
            redisTemplate.expire(OLD_PHONONE_CHANGE_+oldphone,2, TimeUnit.MINUTES);//保存2分钟
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"验证码发送失败");
        }
        return new Result(true,StatusCode.OK,"发送消息成功");
    }

    @PostMapping("/changepassword")
    public Result changePassword(@RequestBody Map map){
        //获取原密码
        String password = (String)map.get("password");
        //获取新密码
        String new_password = (String)map.get("new_password");
        String username = tokenDecode.getUserInfo().get("user_name");  //根据token获取用户名
        User user = userService.findById(username);
        String sqlpass = user.getPassword();
        boolean matches = passwordEncoder.matches(password,sqlpass);
        if (matches){
            System.out.println("密码匹配成功");
            user.setPassword(passwordEncoder.encode(new_password));
            userService.update(user);
            System.out.println("密码修改成功");
            return new Result(true,StatusCode.OK,"密码修改成功");
        }else {
            return new Result(false,StatusCode.ERROR,"原密码输入错误");
        }

    }

    /**
     * 查询全部数据
     *
     * @return
     */
    @GetMapping
    public Result findAll() {
        List<User> userList = userService.findAll();
        return new Result(true, StatusCode.OK, "查询成功", userList);
    }

    /***
     * 根据ID查询数据
     * @param username
     * @return
     */
    @GetMapping("/{username}")
    public Result findById(@PathVariable String username) {
        User user = userService.findById(username);
        return new Result(true, StatusCode.OK, "查询成功", user);
    }


    /***
     * 新增数据
     * @param user
     * @return
     */
    @PostMapping
    public Result add(@RequestBody User user) {
        userService.add(user);
        System.out.println("用户添加成功");
        return new Result(true, StatusCode.OK, "添加成功");
    }


    /***
     * 修改数据
     * @param user
     * @param username
     * @return
     */
    @PutMapping(value = "/{username}")
    public Result update(@RequestBody User user, @PathVariable String username) {
        user.setUsername(username);
        userService.update(user);
        return new Result(true, StatusCode.OK, "修改成功");
    }


    /***
     * 根据ID删除品牌数据
     * @param username
     * @return
     */
    @DeleteMapping(value = "/{username}")
    public Result delete(@PathVariable String username) {
        userService.delete(username);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    /***
     * 多条件搜索品牌数据
     * @param searchMap
     * @return
     */
    @GetMapping(value = "/search")
    public Result<List<User>> findList(@RequestParam Map searchMap) {
        List<User> list = userService.findList(searchMap);
        return new Result(true, StatusCode.OK, "查询成功", list);
    }


    /***
     * 分页搜索实现
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}")
    public Result findPage(@RequestParam Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<User> pageList = userService.findPage(searchMap, page, size);
        PageResult pageResult = new PageResult(pageList.getTotal(), pageList.getResult());
        return new Result(true, StatusCode.OK, "查询成功", pageResult);
    }

    //根据用户名查询用户信息
    @GetMapping("/load/{username}")
    public Result<User> findByUsername(@PathVariable("username") String username) {
        User user = userService.findById(username);
        return new Result(true, StatusCode.OK, "查询成功", user);
    }

    /**
     * 头像上传,保存图片路径
     */
    @PutMapping("/edit/headPic")
    public Result editHeadPic(@RequestParam("headPic") String headPic) {
        String username = tokenDecode.getUserInfo().get("user_name");  //根据token获取用户名
        userService.editHeadPic(username, headPic);
        return new Result(true, StatusCode.OK, "编辑成功");
    }


    /**
     * 编辑用户信息
     */
    @PostMapping("/edit/editUserInfo")
    public Result editUserInfo(@RequestBody Map<String, String> map) {
        String username = tokenDecode.getUserInfo().get("user_name");  //根据token获取用户名
        userService.editUserInfo(username, map);
        return new Result(true, StatusCode.OK, "编辑成功");
    }

    @GetMapping("/userReport")
    public Result findUser() {
        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();
        //获得日历对象
        Calendar calendar = Calendar.getInstance();
        //获得当前时间往前推12个月
        calendar.add(Calendar.MONTH, -12);
        //计算过去一年的12个月 分别的月份
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }
        map.put("months", months);

        List<Integer> userCount = userService.findMemberCountByMonths(months);
        map.put("userCount", userCount);
        return new Result(true, StatusCode.OK, "查询成功", map);
    }

}
